using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using BootstrapBlazor.Components;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Pangeo.Admin.Models;
using BlazorAdmin.Services.DbService;

namespace BlazorAdmin.Services
{
    /// <summary>
    /// Tasks 服务
    /// </summary>
    public class JobService : BaMgmtDbService, IJob
    {
        public JobService(IPetaPoco db) : base(db) { }

        /// <summary>
        /// 保存、更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>错误消息</returns>
        public async Task<string> Save(Job entity)
        {
            using var db = Create();
            bool isUpdate = entity.ID > 0;

            try
            {
                if (isUpdate)
                {
                    var prvEntity = db.FirstOrDefault<Job>($"where ID = {entity.ID}");

                    if(entity.LastExecTime == null && prvEntity.LastExecTime != null)
                    {
                        entity.LastExecTime = prvEntity.LastExecTime;
                        entity.LastExecResult = prvEntity.LastExecResult;
                    }

                    db.Update(entity);
                }
                else
                {
                    db.Insert(entity);
                }
            }
            catch(Exception ex)
            {
                return $"保存出错，{ex.Message}";
            }

            return string.Empty;
        }

        public Task<List<Job>> Query(JobStatus status)
        {
            using var db = Create();
            var list = db.Query<Job>("Where Status = @0", status.ToString()).ToList();

            return Task.FromResult(list);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询参数集合</param>
        /// <returns>分页数据</returns>
        public async Task<QueryData<Job>> Query(AppQueryOption query)
        {
            var strSql = $"Select * From Jobs Where 1 = 1";

            query.Sql = new(strSql, new { param = "value" });

            //注意：多表关联查询，需删除下面这行（默认false），否则过滤、查询会被当做内联查询，影响效率
            query.Sql.IsSingleTable = true;

            //注意：如果只查单表，且没有任何自定义参数，可以删除上面所有代码，直接return PageQueryAsync即可
            return await PageQueryAsync<Job>(query);
        }

        /// <summary>
        /// 物理删除实例
        /// </summary>
        /// <param name="ids">主键id集合</param>
        /// <returns></returns>
        public async Task<bool> Delete(List<int> ids)
        {
            using var db = Create();
            var rows = db.Delete<Job>($"where ID in ({string.Join(",", ids)})");

            return rows > 0;
        }
    }
}
